package com.smartwheel.db.mongo;

import com.mongodb.*;
import com.mongodb.util.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

class DriveDao {

    private static final Logger LOG = LoggerFactory.getLogger(DriveDao.class);

    void storeList(DBCollection col, String info) {
        LOG.debug("Storing : " + info);
        BasicDBList objectsList = (BasicDBList) JSON.parse(info);
        if (objectsList != null) {
            for (Object anObjectsList : objectsList) {
                col.insert((DBObject) anObjectsList);
            }
        } else {
            LOG.warn("Received an null list");
        }
    }

    void storeObject(DBCollection col, String info) {
        LOG.debug("Storing : " + info);
        BasicDBObject jsonObject = (BasicDBObject) JSON.parse(info);
        if (jsonObject != null) {
            col.insert((DBObject) jsonObject);
        } else {
            LOG.warn("Received an null object");
        }
    }

    String find(DBCollection col, long startTimestamp, long endTimestamp) {
        BasicDBObject query = new BasicDBObject();
        query.put(DbDef.TIME_COL_NAME, new BasicDBObject("$gte", startTimestamp).append("$lte", endTimestamp));
        LOG.debug("Search query: " + query.toString());
        DBCursor cursor = col.find(query).sort(new BasicDBObject("ts", 1));
        return JSON.serialize(cursor);
    }

    String find(DBCollection col, Map<String, String> filters) {
        BasicDBObject query = new BasicDBObject();
        query.putAll(filters);
        DBCursor cursor = col.find(query);
        LOG.debug("Search query: " + query.toString());
        return JSON.serialize(cursor);
    }
}
